package com.happy.ibidding.service;

import com.happy.ibidding.bean.Bid;
import com.happy.ibidding.dao.BidRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class BidService {

    final private BidRepository bidRepository;

    final private UserService userService;

    @Autowired
    public BidService(BidRepository bidRepository, UserService userService) {
        this.bidRepository = bidRepository;
        this.userService = userService;
    }

    public Bid save(Bid bid) {
        return this.bidRepository.save(bid);
    }

    public List<Bid> viewAll() {
        return this.bidRepository.findAll();
    }

    public List<Bid> viewAll(String askId, String userId) {
        List<Bid> bidList = this.viewAll();

        if (Objects.nonNull(askId)) {
            bidList = bidList.parallelStream().filter(each -> each.getAskId().equals(askId)).collect(Collectors.toList());
        }

        if (Objects.nonNull(userId)) {
            bidList = bidList.parallelStream().filter(each -> each.getUserId().equals(userId)).collect(Collectors.toList());
        }

        bidList.forEach(each->each.setUser(this.userService.findUserByUserId(each.getUserId())));

        return bidList;
    }

    public void deleteBid(String mongodbId){
        this.bidRepository.deleteById(mongodbId);
    }

}
